import { useEffect } from 'react';
import Taro, { useLoad, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
import Placeholder from 'components/Placeholder';
import {articleListApi} from './api'
import useFetch from 'hooks/useFetch';
import s from './index.module.scss'
import useAlbumAuth from 'hooks/useAlbumAuth';

export default function Index() {
  const {params} = useRouter();
  let {title, _id = ''} = params;

  const auth = useAlbumAuth(_id)
  
  useLoad((option) => {
    _id = option._id
  })

  const {data, loading} = useFetch(articleListApi, _id)

  var __title = decodeURIComponent(title || '目录')

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: __title
    })
  }, [])

  useShareAppMessage(() => {
    return {
      title: __title,
      path: `pages/directory/index?_id=${_id}`
    }
  })

  useShareTimeline(() => ({
    title: __title,
    path: `pages/directory/index?_id=${_id}`
  }))

  function jumptoWebview(item) {
    var _item = auth ? item : data[0]
    const {title, url} = _item

    const __title = encodeURIComponent(title)
    const __url = encodeURIComponent(url)

    let __path = `/pages/webview/index?url=${__url}&title=${__title}`;
    
    Taro.navigateTo({
      url: __path
    })
  }

  console.log(window.eval)

  return (
    <view style={window.eval as any}>
      <view id={s.wrapper}>
        {loading ? <view id={s.tip}>数据请求中...</view> : (
          <>
            <view className={s.top}>共<i className={s.italic}>{data.length}</i> 篇</view>
            {data.length === 0 && (
              <view id={s.tip}>
                内容创作中，目前暂无数据，请耐心等待！
              </view>
            )}
            {data.map((item, index) => (
              <div id={s.item} key={item._id} onClick={() => jumptoWebview(item)}>
                <div id={s.index}>{index + 1}</div>
                <div id={s.title}>{item.title}</div>
              </div>
            ))}
          </>
        )}
      </view>
      <Placeholder type='statusBar' />
    </view>
  )
}
